from os import path
from jinja2 import Environment, FileSystemLoader
from werkzeug import Response, Local, LocalManager
from werkzeug.routing import Map, Rule
from decorator import decorator
import simplejson


TEMPLATE_PATH = path.join(path.dirname(__file__), 'templates')
STATIC_PATH = path.join(path.dirname(__file__), 'static')
ALLOWED_SCHEMES = frozenset(['http', 'https', 'ftp', 'ftps'])
URL_CHARS = 'abcdefghijkmpqrstuvwxyzABCDEFGHIJKLMNPQRST23456789'

local = Local()
local_manager = LocalManager([local])
application = local('application')

url_map = Map([Rule('/static/<file>', endpoint='static', build_only=True)])

jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_PATH))


def expose(rule, **kw):
  def decorate(f):
    kw['endpoint'] = f.__name__
    url_map.add(Rule(rule, **kw))
    return f
  return decorate

def url_for(endpoint, _external=False, **values):
  return local.url_adapter.build(endpoint, values, force_external=_external)
jinja_env.globals['url_for'] = url_for

def render_template(template, **context):
  return Response(jinja_env.get_template(template).render(**context),
                  mimetype='text/html')

def jsonify(func, *args, **kwargs):
  data = func(*args, **kwargs)
  return Response(simplejson.dumps(data))
jsonify = decorator(jsonify)
